<?php
/**
 * Created by PhpStorm.
 * User: superlee
 * Date: 2019/11/16
 * Time: 18:43
 */

namespace app\admin\controller;
use app\admin\model\Purchase as PurchaseModel;
use app\admin\model\PurchaseGoods as PurchaseGoodsModel;
use Carbon\Carbon;
use think\Request;
use think\Db;

class Purchase extends Common
{
    public $time = '';
    public function purchase_list () {
        return $this->fetch();
    }

    public function manual_add_purchase () {
        $purchase_sn = self::create_purchase_sn();
        $this->assign('purchase_sn',$purchase_sn);
        $this->assign('add_user',session('admin_name'));
        if(request()->isPost()){
            $purchase = (array)json_decode(input('post.purchase'));
            $goods_list = (array)json_decode(input('post.goods_list'));
            if(!$goods_list){
                return $this->returnApiData(self::CODE_COMMON_ERROR, [], '缺少采购商品数据。');
            }
            foreach ($goods_list as $key => $value){
                $goods_list[$key] = (array)$value;
            }
            $puchase_note = 'purchase:' . input('post.purchase') . 'goods_list:' . input('post.goods_list');
            Db::startTrans();
            try{
                //添加采购单
                $puchase_id = self::save_purchase($purchase);
                //添加采购单商品
                $add_puchase_goods = self::save_purchase_goods($puchase_id, $goods_list);
                Db::commit();
                self::insert_purchase_log($puchase_id,$puchase_note,session('admin_id'));
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->returnApiData(self::CODE_COMMON_ERROR, [], '-2 系统错误，请联系管理员。');
            }
            return $this->returnApiData(self::CODE_COMMON_SUCCESS, [] , '新增采购单成功');
        }
        return $this->fetch();
    }

    public function auto_add_purchase () {
        return $this->fetch();
    }

    private function save_purchase_goods ($puchase_id=0,$goods_list){
        if($puchase_id==0){
            return $this->returnApiData(self::CODE_COMMON_ERROR, [], '-1 参数错误，请联系管理员。');
        }
        $i=0;
        foreach ($goods_list as $key=>$value){
            $goods_list[$i]['purchase_id'] = $puchase_id;
            $goods_list[$i]['goods_id'] = $key;
            $goods_list[$i]['in_goods_number'] = $value['goods_number'];
            $goods_list[$i]['in_goods_price'] = $value['price'];
            $goods_list[$i]['add_time'] = $this->time->timestamp;
            $goods_list[$i]['state'] = 0;
            unset($goods_list[$key]);
            $i++;
        }
        $insert = db('purchase_goods')->insertAll($goods_list);
        return $insert;
    }

    private function save_purchase ($purchase) {
        $purchase['add_admin_id'] = session('admin_id');
        $purchase['add_time'] = $this->time->timestamp;
        $purchase['add_purchase_date'] = strtotime($purchase['add_purchase_date']);
        $add_purchase = PurchaseModel::create($purchase);
        $puchase_id = $add_purchase->getLastInsID();
        return $puchase_id;
    }

    private function create_purchase_sn ($type=1){
        $S_prefix = $type == 1 ? 'M-' : 'A-';
        $time = Carbon::now(config('default_timezone'))->locale('zh_cn');
        $purchase_sn = $S_prefix . substr($this->time->year,2) . $this->time->month . $this->time->day . '-' .$this->time->micro;
        return $purchase_sn;
    }

    private function insert_purchase_log ($puchase_id,$puchase_note,$admin_id) {
        $data = [
            'puchase_id'=>$puchase_id,
            'puchase_note'=>$puchase_note,
            'admin_id'=>$admin_id,
            'add_time'=>$this->time->timestamp
        ];
        db('purchase_log')->insert($data);
    }

    public function __construct(Request $request = null)
    {
        $this->time = Carbon::now(config('default_timezone'))->locale('zh_cn');
        parent::__construct($request);
    }
}